//
//  ShowViewController.m
//  Baidu
//
//  Created by C_HAO on 15/4/2.
//  Copyright (c) 2015年 C_HAO. All rights reserved.
//

#import "ShowViewController.h"
#import "AFNetworking.h"
#import "AppDelegate.h"
#import "UserPreferences.h"
#import "NSString+Code.h"
#import "AFURLSessionManager.h"



@interface ShowViewController () <NSTextViewDelegate>

@property(nonatomic, retain)IBOutlet NSTextView *handleTextView;

@property(nonatomic, copy)NSMutableAttributedString *baiduTextStorage;

@property(nonatomic, copy)NSMutableAttributedString *youdaoTextStorage;

@property(nonatomic, assign)NSInteger order;

@end

@implementation ShowViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do view setup here.
    _sourceTextView.font = [NSFont systemFontOfSize:20];
    _sourceTextView.maxSize = CGSizeMake(_sourceTextView.frame.size.width, 10000);
    _sourceTextView.verticallyResizable = YES;
}


- (BOOL)textView:(NSTextView *)textView shouldChangeTextInRanges:(NSArray *)affectedRanges replacementStrings:(NSArray *)replacementStrings
{
    NSString *string = [replacementStrings lastObject];
    if ([string isEqualToString:@"\n"]) {
        NSString *text = [NSString stringWithFormat:@"%@",[textView string]];
        [_handleTextView setString:@""];
        [self interpretAPI:text];
        if (_block) _block(_sourceTextView,_handleTextView);
        return NO;
    }
    return YES;
}

- (NSString *)baiduAPI:(NSString *)text
{
    BOOL zh = [self validateCharacters:text];
    NSString *salt = [NSString stringWithFormat:@"%u",(arc4random() % 10000) + 89999];
    NSString *signMD5 = [NSString stringWithFormat:@"20151119000005851%@%@2GO7WhYhBRVEznjQPUAs",[text encodeUTF8String],salt].MD5;
    NSString *argument = [NSString stringWithFormat:@"q=%@&from=%@&to=%@&appid=20151119000005851&salt=%@&sign=%@", [text encodeUTF8String], zh? @"zh" : @"en", zh? @"en" : @"zh", salt, signMD5];
    
    return [[@"http://api.fanyi.baidu.com/api/trans/vip/translate?" stringByAppendingString:argument] urlEncodeUTF8String];
}

- (NSString *)youdaoAPI:(NSString *)text
{
    return [@"http://fanyi.youdao.com/openapi.do?keyfrom=testotherAPI&key=521472132&type=data&doctype=json&version=1.1&q=" stringByAppendingString:[text urlEncodeUTF8String]];
}

- (BOOL)validateCharacters:(NSString *)textString
{
    NSString *characters= @"^[\u4E00-\u9FA5]*$";
    NSPredicate *charactersPre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",characters];
    return [charactersPre evaluateWithObject:textString];
}


- (void)interpretAPI:(NSString *)sourceText
{
    _order = 0;
    if ([AppDelegate appDelegate].preferences.youdao) {
        _youdaoTextStorage = nil;
        [self translation:sourceText];
    }
    
    if ([AppDelegate appDelegate].preferences.baidu) {
        _baiduTextStorage = nil;
        [self baiduTranslation:sourceText];
    }
}

//有道翻译
- (void)translation:(NSString *)sourceText
{
    if (!sourceText.length) {
        return;
    }
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[self youdaoAPI:sourceText]]];
    
    __weak typeof(self) VC = self;
    NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (error) {
            
        } else {
            __strong typeof(VC) SVC = VC;
            [SVC analysis:responseObject isBaiDu:NO];
        }
    }];
    [dataTask resume];
    
}


//百度翻译
- (void)baiduTranslation:(NSString *)sourceText
{
    if (!sourceText.length) {
        return;
    }
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[self baiduAPI:sourceText]]];
    
    __weak typeof(self) VC = self;
    NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (error) {
            
        } else {
            __strong typeof(VC) SVC = VC;
            [SVC analysis:responseObject isBaiDu:YES];
        }
    }];
    [dataTask resume];
}

- (id)analysis:(NSData *)json
{
    if (!json) {
        return nil;
    }
    
    NSError *err;
    id jsonStr = [NSJSONSerialization JSONObjectWithData:json options:NSJSONReadingMutableContainers error:&err];
    
    if (err) {
        return json;
    }
    
    return jsonStr;
}


- (void)analysis:(id)responseObject isBaiDu:(BOOL)baiDu
{
    @synchronized(self) {
        if (baiDu) {
            
            
            NSString *errorCode = [responseObject objectForKey:@"error_code"];
            
            switch ([errorCode integerValue]) {
                case 0:
                case 52000: {
                    
                    _order = (_order == 0)? 1 : _order;
                    
                    _baiduTextStorage = [NSMutableAttributedString new];
                    
                    NSMutableAttributedString *nameString = [[NSMutableAttributedString alloc] initWithString:@"百度翻译\n"];
                    [nameString addAttribute:NSForegroundColorAttributeName value:[NSColor colorWithRed:51/255.0 green:177/255.0 blue:255/255.0 alpha:1] range:NSMakeRange(0, [nameString length])];
                    [nameString addAttribute:NSFontAttributeName value:[NSFont systemFontOfSize:18] range:NSMakeRange(0, [nameString length])];
                    [_baiduTextStorage appendAttributedString:nameString];
                    [_baiduTextStorage appendAttributedString:[[NSMutableAttributedString alloc] initWithString:@"\n"]];
                    
                    NSArray *trans = [responseObject objectForKey:@"trans_result"];
                    for (NSDictionary *src in trans) {
                        NSString *dst = [[src objectForKey:@"dst"] urlDecodeUTF8String];
                        if (dst) {
                            NSMutableAttributedString *attriString = [[NSMutableAttributedString alloc] initWithString:[dst stringByAppendingString:@"\n"]];
                            [attriString addAttribute:NSForegroundColorAttributeName value:[NSColor blackColor] range:NSMakeRange(0, [attriString length])];
                            [attriString addAttribute:NSFontAttributeName value:[NSFont systemFontOfSize:20] range:NSMakeRange(0, [attriString length])];
                            [_baiduTextStorage appendAttributedString:attriString];
                        }
                        
                    }
                    [_baiduTextStorage appendAttributedString:[[NSMutableAttributedString alloc] initWithString:@"\n"]];
                }
                    break;
                default: {
                    
                    _order = (_order == 0)? 1 : _order;
                    
                    _baiduTextStorage = [NSMutableAttributedString new];
                    
                    NSMutableAttributedString *nameString = [[NSMutableAttributedString alloc] initWithString:@"百度翻译\n"];
                    [nameString addAttribute:NSForegroundColorAttributeName value:[NSColor colorWithRed:51/255.0 green:177/255.0 blue:255/255.0 alpha:1] range:NSMakeRange(0, [nameString length])];
                    [nameString addAttribute:NSFontAttributeName value:[NSFont systemFontOfSize:18] range:NSMakeRange(0, [nameString length])];
                    [_baiduTextStorage appendAttributedString:nameString];
                    [_baiduTextStorage appendAttributedString:[[NSMutableAttributedString alloc] initWithString:@"\n"]];
                    
                    NSMutableAttributedString *errorCodeString = [[NSMutableAttributedString alloc] initWithString:errorCode];
                    [errorCodeString addAttribute:NSForegroundColorAttributeName value:[NSColor redColor] range:NSMakeRange(0, [errorCodeString length])];
                    [errorCodeString addAttribute:NSFontAttributeName value:[NSFont systemFontOfSize:18] range:NSMakeRange(0, [errorCodeString length])];
                    [errorCodeString appendAttributedString:[[NSMutableAttributedString alloc] initWithString:@"\n"]];
                    
                    [_baiduTextStorage appendAttributedString:errorCodeString];
                    
                    
                    NSMutableAttributedString *errorString = [[NSMutableAttributedString alloc] initWithString:[responseObject objectForKey:@"error_msg"]];
                    [errorString addAttribute:NSForegroundColorAttributeName value:[NSColor redColor] range:NSMakeRange(0, [[responseObject objectForKey:@"error_msg"] length])];
                    [errorString addAttribute:NSFontAttributeName value:[NSFont systemFontOfSize:18] range:NSMakeRange(0, [[responseObject objectForKey:@"error_msg"] length])];
                    [errorString appendAttributedString:[[NSMutableAttributedString alloc] initWithString:@"\n"]];
                    
                    [_baiduTextStorage appendAttributedString:errorString];
                    
                }
                    break;
            }
            
            
            
        }else {
            
            _order = (_order == 0)? 2 : _order;
            
            _youdaoTextStorage = [NSMutableAttributedString new];
            
            NSString *errorCode = [responseObject objectForKey:@"errorCode"];
            
            NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:@""];
            
            if ([errorCode integerValue] == 0) {
                NSMutableAttributedString *nameString = [[NSMutableAttributedString alloc] initWithString:@"有道翻译\n"];
                [nameString addAttribute:NSForegroundColorAttributeName value:[NSColor colorWithRed:51/255.0 green:177/255.0 blue:255/255.0 alpha:1] range:NSMakeRange(0, [nameString length])];
                [nameString addAttribute:NSFontAttributeName value:[NSFont systemFontOfSize:18] range:NSMakeRange(0, [nameString length])];
                [_youdaoTextStorage appendAttributedString:nameString];
                [_youdaoTextStorage appendAttributedString:[[NSMutableAttributedString alloc] initWithString:@"\n"]];
                NSArray *translation = [responseObject objectForKey:@"translation"];
                for (NSString *tr in translation) {
                    NSMutableAttributedString *attriString = [[NSMutableAttributedString alloc] initWithString:[tr stringByAppendingString:@"\n"]];
                    [attriString addAttribute:NSForegroundColorAttributeName value:[NSColor blackColor] range:NSMakeRange(0, [attriString length])];
                    [attriString addAttribute:NSFontAttributeName value:[NSFont systemFontOfSize:20] range:NSMakeRange(0, [attriString length])];
                    [_youdaoTextStorage appendAttributedString:attriString];
                }
                NSDictionary *basic = [responseObject objectForKey:@"basic"];
                NSArray *explains = [basic objectForKey:@"explains"];
                for (NSString *ex in explains) {
                    if ([explains indexOfObject:ex] == 0) {
                        [_youdaoTextStorage appendAttributedString:[[NSMutableAttributedString alloc] initWithString:@"\n"]];
                        NSMutableAttributedString *attriString = [[NSMutableAttributedString alloc] initWithString:@"基本词典 :\n"];
                        [attriString addAttribute:NSForegroundColorAttributeName value:[NSColor grayColor] range:NSMakeRange(0, [attriString length])];
                        [attriString addAttribute:NSFontAttributeName value:[NSFont systemFontOfSize:20] range:NSMakeRange(0, [attriString length])];
                        [_youdaoTextStorage appendAttributedString:attriString];
                        
                        NSMutableAttributedString *spaceString = [[NSMutableAttributedString alloc] initWithString:[ex stringByAppendingString:@"\n"]];
                        [spaceString addAttribute:NSForegroundColorAttributeName value:[NSColor blackColor] range:NSMakeRange(0, [spaceString length])];
                        [spaceString addAttribute:NSFontAttributeName value:[NSFont systemFontOfSize:20] range:NSMakeRange(0, [spaceString length])];
                        [_youdaoTextStorage appendAttributedString:spaceString];
                    }else {
                        NSMutableAttributedString *spaceString = [[NSMutableAttributedString alloc] initWithString:[ex stringByAppendingString:@"\n"]];
                        [spaceString addAttribute:NSForegroundColorAttributeName value:[NSColor blackColor] range:NSMakeRange(0, [spaceString length])];
                        [spaceString addAttribute:NSFontAttributeName value:[NSFont systemFontOfSize:20] range:NSMakeRange(0, [spaceString length])];
                        [_youdaoTextStorage appendAttributedString:spaceString];
                    }
                }
                NSArray *webs = [responseObject objectForKey:@"web"];
                for (NSDictionary *we in webs) {
                    if ([webs indexOfObject:we] == 0) {
                        NSMutableAttributedString *attriString = [[NSMutableAttributedString alloc] initWithString:@"\n网络释义 : \n"];
                        [attriString addAttribute:NSForegroundColorAttributeName value:[NSColor grayColor] range:NSMakeRange(0, [attriString length])];
                        [attriString addAttribute:NSFontAttributeName value:[NSFont systemFontOfSize:20] range:NSMakeRange(0, [attriString length])];
                        [_youdaoTextStorage appendAttributedString:attriString];
                        
                        [_youdaoTextStorage appendAttributedString:[[NSMutableAttributedString alloc] initWithString:@"   " ]];
                        
                        NSMutableAttributedString *spaceString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@ :\n",[we objectForKey:@"key"]]];
                        [spaceString addAttribute:NSForegroundColorAttributeName value:[NSColor blackColor] range:NSMakeRange(0, [spaceString length])];
                        [spaceString addAttribute:NSFontAttributeName value:[NSFont systemFontOfSize:20] range:NSMakeRange(0, [spaceString length])];
                        [_youdaoTextStorage appendAttributedString:spaceString];
                        
                        NSArray *values = [we objectForKey:@"value"];
                        for (NSString *val in values) {
                            NSMutableAttributedString *valString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"      %@\n",val]];
                            [valString addAttribute:NSForegroundColorAttributeName value:[NSColor blackColor] range:NSMakeRange(0, [valString length])];
                            [valString addAttribute:NSFontAttributeName value:[NSFont systemFontOfSize:20] range:NSMakeRange(0, [valString length])];
                            [_youdaoTextStorage appendAttributedString:valString];
                        }
                        
                    }else {
                        [_youdaoTextStorage appendAttributedString:[[NSMutableAttributedString alloc] initWithString:@"   "]];
                        NSMutableAttributedString *spaceString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@ :\n",[we objectForKey:@"key"]]];
                        [spaceString addAttribute:NSForegroundColorAttributeName value:[NSColor blackColor] range:NSMakeRange(0, [spaceString length])];
                        [spaceString addAttribute:NSFontAttributeName value:[NSFont systemFontOfSize:20] range:NSMakeRange(0, [spaceString length])];
                        [_youdaoTextStorage appendAttributedString:spaceString];
                        NSArray *values = [we objectForKey:@"value"];
                        for (NSString *val in values) {
                            NSMutableAttributedString *valString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"      %@\n",val]];
                            [valString addAttribute:NSForegroundColorAttributeName value:[NSColor blackColor] range:NSMakeRange(0, [valString length])];
                            [valString addAttribute:NSFontAttributeName value:[NSFont systemFontOfSize:20] range:NSMakeRange(0, [valString length])];
                            [_youdaoTextStorage appendAttributedString:valString];
                        }
                    }
                }
                
                [_youdaoTextStorage appendAttributedString:text];
                
            }
            if ([errorCode integerValue] == 20) {
                NSMutableAttributedString *attriString = [[NSMutableAttributedString alloc] initWithString:@"要翻译的文本过长"];
                [attriString addAttribute:NSForegroundColorAttributeName value:[NSColor redColor] range:NSMakeRange(0, [attriString length])];
                [attriString addAttribute:NSFontAttributeName value:[NSFont systemFontOfSize:20] range:NSMakeRange(0, [attriString length])];
                [_youdaoTextStorage appendAttributedString:attriString];
            }
            if ([errorCode integerValue] == 30) {
                NSMutableAttributedString *attriString = [[NSMutableAttributedString alloc] initWithString:@"无法进行有效的翻译"];
                [attriString addAttribute:NSForegroundColorAttributeName value:[NSColor redColor] range:NSMakeRange(0, [attriString length])];
                [attriString addAttribute:NSFontAttributeName value:[NSFont systemFontOfSize:20] range:NSMakeRange(0, [attriString length])];
                [_youdaoTextStorage appendAttributedString:attriString];
            }
            if ([errorCode integerValue] == 40) {
                NSMutableAttributedString *attriString = [[NSMutableAttributedString alloc] initWithString:@"不支持的语言类型"];
                [attriString addAttribute:NSForegroundColorAttributeName value:[NSColor redColor] range:NSMakeRange(0, [attriString length])];
                [attriString addAttribute:NSFontAttributeName value:[NSFont systemFontOfSize:20] range:NSMakeRange(0, [attriString length])];
                [_youdaoTextStorage appendAttributedString:attriString];
            }
            if ([errorCode integerValue] == 50) {
                NSMutableAttributedString *attriString = [[NSMutableAttributedString alloc] initWithString:@"无效的key"];
                [attriString addAttribute:NSForegroundColorAttributeName value:[NSColor redColor] range:NSMakeRange(0, [attriString length])];
                [attriString addAttribute:NSFontAttributeName value:[NSFont systemFontOfSize:20] range:NSMakeRange(0, [attriString length])];
                [_youdaoTextStorage appendAttributedString:attriString];
            }
            if ([errorCode integerValue] == 60) {
                NSMutableAttributedString *attriString = [[NSMutableAttributedString alloc] initWithString:@"无词典结果，仅在获取词典结果生效"];
                [attriString addAttribute:NSForegroundColorAttributeName value:[NSColor redColor] range:NSMakeRange(0, [attriString length])];
                [attriString addAttribute:NSFontAttributeName value:[NSFont systemFontOfSize:20] range:NSMakeRange(0, [attriString length])];
                [_youdaoTextStorage appendAttributedString:attriString];
            }
            [_youdaoTextStorage appendAttributedString:[[NSMutableAttributedString alloc] initWithString:@"\n"]];
        }
        
        NSMutableAttributedString *textStorage = [NSMutableAttributedString new];
        
        if (_order == 1) {
            if (_baiduTextStorage) {
                [textStorage appendAttributedString:_baiduTextStorage];
            }
            if (_youdaoTextStorage) {
                [textStorage appendAttributedString:_youdaoTextStorage];
            }
        }
        if (_order == 2) {
            if (_youdaoTextStorage) {
                [textStorage appendAttributedString:_youdaoTextStorage];
            }
            if (_baiduTextStorage) {
                [textStorage appendAttributedString:_baiduTextStorage];
            }
        }

        [[self.handleTextView textStorage] setAttributedString:textStorage];
    }
    
}

@end
